﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.Utils
{
    public static partial class EnumerableExtensions
    {
        public static bool IsEquivalentTo(this IEnumerable first, IEnumerable second)
        {
            var secondList = second.Cast<object>().ToList();
            foreach (var item in first)
            {
                var index = secondList.FindIndex(item.Equals);
                if (index < 0)
                {
                    return false;
                }
                secondList.RemoveAt(index);
            }
            return secondList.Count == 0;
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
            => enumerable == null || !enumerable.Any();

        public static IEnumerable<TResult> PrevCurrentZip<T, TResult>(this IEnumerable<T> stream,
            Func<T, T, TResult> selector) where T : class
        {
            var enumerator = stream.GetEnumerator();
            if (enumerator.MoveNext())
            {
                T prev = null;
                T curr = enumerator.Current;

                while (enumerator.MoveNext())
                {
                    var next = enumerator.Current;
                    yield return selector(prev, curr);
                    prev = curr;
                    curr = next;
                }

                yield return selector(prev, curr);
            }
        }

        public static void PrevCurrentZip<T>(this IEnumerable<T> stream,
            Action<T, T> selector) where T : class
        {
            var enumerator = stream.GetEnumerator();
            if (enumerator.MoveNext())
            {
                T prev = null;
                T curr = enumerator.Current;

                while (enumerator.MoveNext())
                {
                    var next = enumerator.Current;
                    selector(prev, curr);
                    prev = curr;
                    curr = next;
                }

                selector(prev, curr);
            }
        }
    }
}
